<?php


namespace app\admin\system\controller;


use app\admin\system\logic\AdminLogic;
use app\admin\system\logic\RoleLogic;
use app\admin\system\service\AdminService;
use app\common\controller\BaseAdminController;
use app\common\service\PasswordService;
use support\exception\BadException;
use support\utils\RandomUtil;

class AdminController extends BaseAdminController
{

    protected $noNeedRight = [
        'loginUserInfo',
    ];

    protected function init()
    {
        parent::init();
        $this->logic = new AdminLogic();
    }

    public function loginUserInfo()
    {
        $uid = request()->uid;
        $user = $this->logic->getModel()->where([
            'id' => $uid
        ])->withoutField(['password', 'salt'])->find();
        $roles = AdminService::getRoleNames($uid);

        if (AdminService::isSuperAdmin($uid)) {
            $buttons = AdminService::SUPPER_PERMISSION;
            $permissions = AdminService::SUPPER_PERMISSION;
        } else {
            $buttons = AdminService::getAuthority($uid, [3]);
            $permissions = AdminService::getAuthority($uid, [1, 2]);
        }

        $data = [
            'user' => $user,
            'roles' => $roles,
            'buttons' => $buttons,
            'permissions' => $permissions,
        ];
        return $this->success($data);
    }


    public function list()
    {
        $where = [];
        $this->form['username'] && $where[] = ['username', 'like', "%{$this->form['username']}%"];
        $this->form['phone'] && $where[] = ['phone', 'like', "%{$this->form['phone']}%"];
        $this->form['nickname'] && $where[] = ['nickname', 'like', "%{$this->form['nickname']}%"];
        if ($this->form['login_start'] && $this->form['login_end']) {
            $where[] = ['login_time', 'between', $this->form['login_start'], $this->form['login_end']];
        }

        $data = $this->logic->getPageList($this->logic->search($where));
        $role_ids = [];
        array_walk($data['records'], function (&$v) use (&$role_ids) {
            $v['role_ids'] = explode(',', $v['role_ids']);
            $role_ids = array_merge($role_ids, $v['role_ids']);
        });
        $roleLogic = new RoleLogic();
        $roleMap = $roleLogic->where('roleId', 'in', $role_ids)
            ->column('roleName', 'roleId');
        array_walk($data['records'], function (&$v) use ($roleMap) {
            $roles = [];
            foreach ($v['role_ids'] as $id) {
                if ($rr = $roleMap[$id] ?? "") {
                    $roles[] = $rr;
                }
            }
            $v['roles'] = $roles;
        });

        return $this->success($data);
    }

    public function add()
    {
        $data = request()->post();
        $salt = RandomUtil::randomLetter(10);
        $data['password'] = PasswordService::getPassword("123456", $salt);
        $data['salt'] = $salt;
        if ($this->validate) {
            if (!$this->validate->scene('add')->check($data)) {
                return $this->error($this->validate->getError());
            }
        }
        $result = $this->logic->save($data);
        if ($result) {
            return $this->success();
        } else {
            return $this->error();
        }
    }

    public function update()
    {
        $data = request()->post();
        $id = request()->input('id');
        $salt = RandomUtil::randomLetter(10);
        $data['password'] = PasswordService::getPassword("123456", $salt);
        $data['salt'] = $salt;
        if ($this->validate) {
            if (!$this->validate->scene('add')->check($data)) {
                return $this->error($this->validate->getError());
            }
        }
        $result = $this->logic->update($data, [$this->idKey => $id]);
        if ($result) {
            return $this->success();
        } else {
            return $this->error();
        }
    }

    public function getById()
    {
        $id = input('id');
        $data = $this->logic->getModel()->withoutField('password')->where('id', '=', $id)->find();
        return $this->success($data);
    }

    public function resetPwd()
    {
        $id = input('id');
        if (!$id) {
            throw new BadException("参数错误");
        }
        $salt = RandomUtil::randomLetter(10);
        $data['password'] = PasswordService::getPassword(123456, $salt);
        $data['salt'] = $salt;
        $this->logic->update($data, [
            'id' => $id
        ]);
        return $this->success();
    }
}